package com.gxxy.spring.kp04_integration.cls01_jdbc;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.ResultSetExtractor;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.support.JdbcDaoSupport;

public class StudentDaoImpl extends JdbcDaoSupport implements IStudentDao {

	@Override
	public void save(Student stu) {
		String sql = "INSERT INTO student (name, fees) VALUES (?, ?)";
		getJdbcTemplate().update(sql, stu.getName(), stu.getFees());
	}

	@Override
	public void delete(Student stu) {
		String sql = "DELETE FROM student WHERE id = ?";
		getJdbcTemplate().update(sql, stu.getId());
	}

	@Override
	public void update(Student stu) {
		String sql = "UPDATE student SET name = ?, fees = ? WHERE id = ?";
		getJdbcTemplate().update(sql, stu.getName(), stu.getFees(), stu.getId());
	}

	@Override
	public Student get(Student stu) {
		String sql = "SELECT * FROM student WHERE id = ?";
		Student student = getJdbcTemplate().query(sql,
				new ResultSetExtractor<Student>() {

					@Override
					public Student extractData(ResultSet set)
							throws SQLException, DataAccessException {
						Student stu = null;
						if (set.next()) {
							stu = new Student();
							stu.setId(set.getLong("id"));
							stu.setName(set.getString("name"));
							stu.setFees(set.getDouble("fees"));
							return stu;
						}

						return stu;
					}

				}, stu.getId());

		return student;
	}

	@Override
	public List<Student> list() {
		String sql = "SELECT * FROM student";
		List<Student> stus = getJdbcTemplate().query(sql, new RowMapper<Student>() {

			@Override
			public Student mapRow(ResultSet set, int rowNum)
					throws SQLException {

				Student stu = new Student();
				stu.setId(set.getLong("id"));
				stu.setName(set.getString("name"));
				stu.setFees(set.getDouble("fees"));
				return stu;

			}

		});

		return stus;
	}

}
